#include "./../inc/music.h"

Music *Music::m_instance = NULL;
Music *Music::instance()
{
    // 如果没有实例则创建实例
    if (m_instance == NULL)
    {
        m_instance = new Music();
    }
    return m_instance;
}

void Music::delInstance()
{
    // 释放实例空间
    delete m_instance;
    m_instance = NULL;
}

void Music::playMainMusic()
{
    stopMusic();

    pid_t pid = fork(); // 创建子进程
    if (pid == 0)
    { // 子进程：执行 madplay
        execlp("madplay", "madplay", "-q", main_music_path.data(), NULL);
        perror("execlp madplay failed");
        exit(1); // execlp 失败时，退出子进程（避免变成僵尸进程）
    }
    else if (pid > 0)
    {
        music_pid = pid;
    }
}

void Music::playGameMusic()
{
    stopMusic();

    pid_t pid = fork();
    if (pid == 0)
    {
        execlp("madplay", "madplay", "-q", game_music_path.data(), NULL);
        perror("execlp madplay failed");
        exit(1);
    }
    else if (pid > 0)
    {
        music_pid = pid;
    }
}

void Music::stopMusic()
{
    if (music_pid > 0)
    {
        kill(music_pid, SIGTERM);          // 终止子进程
        waitpid(music_pid, NULL, WNOHANG); // 回收子进程，避免僵尸进程
        music_pid = 0;                     // 重置进程ID
    }

    if (system("pgrep madplay > /dev/null 2>&1") == 0)
    {
        system("killall madplay");
    }
}